<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" :disabled="!checkPermission('exportEmployee')" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" :disabled="!checkPermission('addEmployee')" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="UserList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="avatar" @click="showAvatar(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />

          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry |formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch :value="row.enableState===1" />

            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delUser(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="page.size" :total="page.total" @current-change="currentChange" />
        </el-row>
      </el-card>

      <!-- 弹窗 -->
      <AddEmployee :show-dialog="showDialog" />

      <el-dialog title="头像" :visible="isShowAvatar" @close="guanbi">
        <el-row type="flex" justify="center">
          <canvas ref="myAvatar" />
        </el-row>
      </el-dialog>

      <!-- 角色弹窗 -->
      <assignRole ref="assignRole" :show-dialog.sync="showAssignRole" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getUserList } from '@/api/user'
import employeeEnum from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import { delEmployee } from '@/api/employees'
import AddEmployee from './components/add-employee.vue'
import QRCode from 'qrcode'
import assignRole from './components/assign-role.vue'
export default {
  components: {
    AddEmployee, assignRole
  },
  data() {
    return {
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      UserList: [], // 员工列表
      isShowAvatar: false,
      showDialog: false, // 控制弹窗显示
      showAssignRole: false,
      userId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 导出
    async exportExcel() {
      // 拿到全部员工数据
      const { rows } = await getUserList({ page: 1, size: this.page.total })
      console.log(rows)

      // 根据生成 excel 插件需要, 转换数据
      const header = [
        '手机号',
        '姓名',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const data = rows.map(userObj => {
        return this.obj2arr(userObj, header)
      })
      // 导出
      export_json_to_excel({
        header,
        data
      })
    },
    obj2arr(userObj, header) {
      const userArr = []
      // 将用户对象里面的数据
      // 按照表头的顺序, 逐个放入到数组中
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      header.forEach(key => {
        const enKey = dict[key]
        let value = userObj[enKey]
        if (enKey === 'formOfEmployment') {
          // 如果是聘用形式，用枚举处理
          const obj = employeeEnum.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 格式化日期
          value = formatDate(value)
        }
        userArr.push(value)
      })
      return userArr
    },

    // 请求员工列表
    async getUserList() {
      const { rows, total } = await getUserList(this.page)
      this.page.total = total
      // 数据库缺少了 enableState数据  自己加一个  方便测试
      this.UserList = rows.map(item => {
        return {
          ...item,
          enableState: item.enableState || 1
        }
      })
    },
    // 翻页切换
    currentChange(currentPage) {
      this.page.page = currentPage
      this.getUserList()
    },

    // 格式化
    formOfEmployment(row, column, cell, index) {
      // 枚举数据
      // const hireType = [
      //   { id: 1, value: '正式工' },
      //   { id: 2, value: '临时工' },
      //   { id: 1, value: '实习工' }
      // ]

      const obj = employeeEnum.hireType.find(item => item.id === cell)
      return obj ? obj.value : '未知'
    },

    // 点击删除员工
    async delUser(id) {
      try {
        // 询问
        await this.$confirm('是否确认删除！')
        // 发送请求
        await delEmployee(id)
        // 提示
        this.$message.success('删除成功')
        // 刷新
        this.getUserList()
      } catch (error) {
        console.log(error)
      }
    },

    // 点击头像
    showAvatar(url) {
      if (url) {
        this.isShowAvatar = true

        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myAvatar, url, {
            width: 300
          })
        })
      }
    },
    // 关闭
    guanbi() {
      this.isShowAvatar = false
    },
    async assignRole(id) {
      this.userId = id
      // 角色
      await this.$refs.assignRole.getCheckedRole(id)
      this.showAssignRole = true
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 180px;
  height: 140px;
  object-fit: cover;
}
</style>
